﻿<%@ WebHandler Language="C#" Class="OSSHandler" %>

using System;
using System.Web;
using Aliyun.OSS;
using Newtonsoft.Json.Linq;
using Aliyun.OSS.OSSHelper;

public class OSSHandler : IHttpHandler
{
    public static string _id { get { return OSSConfig.AccessKeyId; } }  //AccessKeyId
    public static string _key { get { return OSSConfig.AccessKeySecret; } }  //AccessKeySecret
    public static string _host { get { return OSSConfig.HOST; } }
    public static string _dir { get { return OSSConfig.Dir; } }

    public JObject GetKey()
    {


        OssClient client = new OssClient(_host, _id, _key);
        DateTime now = DateTime.Now;
        DateTime ex = now.AddSeconds(30);
        PolicyConditions policyConds = new PolicyConditions();
        policyConds.AddConditionItem("content-length-range", 0L, 1048576000L);
        policyConds.AddConditionItem(MatchMode.StartWith, "key", _dir);

        String postPolicy = client.GeneratePostPolicy(ex, policyConds);
        byte[] binaryData = System.Text.Encoding.Default.GetBytes(postPolicy);
        String encodedPolicy = Convert.ToBase64String(binaryData);
        //改到这里的时候遇到的一个坑 Java 里用的是SDK里: client.calculatePostSignature 方法生成签名,但是.NET-SDK好像没有用来生成签名的方法(难道是我找的不够仔细?).没办法又下载了PHP版本找到签名那段:
        //$signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

        var hmac = new System.Security.Cryptography.HMACSHA1(System.Text.Encoding.UTF8.GetBytes(_key));
        var hashBytes = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(encodedPolicy));
        var Signature = Convert.ToBase64String(hashBytes);

        //{"callbackUrl":"http://oss-demo.aliyuncs.com:23450",
        //"callbackHost":"oss-demo.aliyuncs.com",
        //"callbackBody":"filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}",
        //"callbackBodyType":"application/x-www-form-urlencoded"}
        JObject JCallBack = new JObject();
        JCallBack.Add("callbackUrl", "http://oss.ekezhang.com:80/OSS/OSSBackHandler.ashx");
        //JCallBack.Add("callbackHost", _host);
        JCallBack.Add("callbackBody", "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");

        JCallBack.Add("callbackBodyType", @"application/x-www-form-urlencoded");
        JObject obj = new JObject();
        obj.Add("accessid", _id);
        obj.Add("policy", encodedPolicy);
        obj.Add("signature", Signature);
        obj.Add("dir", _dir);
        obj.Add("callback", stringToBase64(JCallBack.ToString()));
        obj.Add("host", _host);
        obj.Add("expire", ConvertDateTimeInt(ex).ToString());
        return obj;
    }
    private string stringToBase64(string str)
    {

        byte[] b = System.Text.Encoding.Default.GetBytes(str);
        //转成 Base64 形式的 System.String  
        return Convert.ToBase64String(b); 
    }
    /// <summary>
    /// DateTime时间格式转换为Unix时间戳格式
    /// </summary>
    /// <param name="time"> DateTime时间格式</param>
    /// <returns>Unix时间戳格式</returns>
    public static int ConvertDateTimeInt(System.DateTime time)
    {
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
        return (int)(time - startTime).TotalSeconds;
    }
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write(GetKey().ToString());
    }


    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}